package com.example.demo.common.advice;

import com.example.demo.common.pojo.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

//统一结果返回
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @SneakyThrows//lombok提供的注解,加上后表示在整个方法上加上了try catch
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //String  Result, body指的是目标方法返回的结果
        if(body instanceof Result<?>){//如果body已经是Result类型了,直接返回body
            return body;
        }
        //对String特殊处理,通常情况下,我们不返回string类型
        if(body instanceof String){//如果是string类型,将string类型转化为Result类型,再返回
            return objectMapper.writeValueAsString(Result.ok(body));
        }//writeValueAsString是将string类型转化为json

        return Result.ok(body);
    }
}
